package cn.aitrox.ry.util;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.gson.JsonObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class NetUtil {
    private static Logger log = LoggerFactory.getLogger(NetUtil.class);

    public NetUtil() {
    }

    public static String getUrlName(String url) {
        String result = url.substring(url.lastIndexOf("/") + 1);
        int index = result.indexOf("?");
        if (index > 0) {
            result = result.substring(0, index);
        }

        return result;
    }

    public static void downloadFileV2(URL url, File file) throws IOException {
        byte[] buffer = new byte[8192];
        BufferedInputStream bin = new BufferedInputStream(url.openStream());
        BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file));

        int read;
        while((read = bin.read(buffer)) > -1) {
            bout.write(buffer, 0, read);
        }

        bout.flush();
        bout.close();
    }

    public static void downloadFileV2(URL url, String savePath, String name) throws IOException {
        File file = new File(savePath, name);
        downloadFileV2(url, file);
    }

    private static URL encodeUrl(String spec) {
        try {
            String url = URLEncoder.encode(spec, "UTF-8");
            url = url.replace("%2F", "/").replace("%3A", ":").replace("%40", "@");
            return new URL(url);
        } catch (Exception var2) {
            return null;
        }
    }

    public static InputStream getFileInputStream(String urlString) {
        InputStream is = null;
        HttpURLConnection conn = null;

        try {
            URL url = encodeUrl(urlString);
            conn = (HttpURLConnection)url.openConnection();
            conn.connect();
            is = conn.getInputStream();
        } catch (Exception var4) {
            log.info(LogUtil.genException(var4));
        }

        return is;
    }

    public static boolean downloadFile(String spec, String savePath, String name, NetUtil.IDownloadListener downloadListener) {
        try {
            URL url = encodeUrl(spec);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.connect();
            int length = conn.getContentLength();
            if (conn.getResponseCode() >= 400) {
                if (downloadListener != null) {
                    downloadListener.onFail(String.valueOf(conn.getResponseCode()));
                }

                return false;
            } else {
                InputStream is = conn.getInputStream();
                File file = new File(savePath, name);
                FsUtil.ensureDirExist(file);
                FileOutputStream fos = new FileOutputStream(file);
                int count = 0;
                byte[] buf = new byte[1024];
                boolean cancelUpdate = false;

                do {
                    int numread = is.read(buf);
                    if (numread <= 0) {
                        if (downloadListener != null) {
                            downloadListener.onFinish();
                        }
                        break;
                    }

                    fos.write(buf, 0, numread);
                    count += numread;
                    int progress = (int)((float)count / (float)length * 100.0F);
                    if (downloadListener != null) {
                        downloadListener.onProgress(progress);
                    }

                    if (downloadListener != null) {
                        cancelUpdate = downloadListener.getCancelUpdate();
                    }
                } while(!cancelUpdate);

                fos.close();
                is.close();
                return true;
            }
        } catch (Exception var15) {
            if (downloadListener != null) {
                downloadListener.onFail(var15.getMessage());
            }

            return false;
        }
    }

    public static JsonObject httpPost(String url, JsonObject jsonParam, String logTitle) {
        return httpPost(url, jsonParam, false, logTitle);
    }

    public static String httpPostMap(String url, Map map, String logTitle) {
        return httpPostString(url, JSONUtil.toJson(map), "application/json", false, logTitle);
    }

    public static String httpPostReturnSb(String url, JsonObject jsonParam, String logTitle) {
        return httpPostString(url, jsonParam, false, logTitle);
    }

    public static String httpPostString(String url, String data, String logTitle) {
        return httpPostString(url, data, (String)null, false, logTitle);
    }

    public static String httpPostString(String url, String data, String contentType, String logTitle) {
        return httpPostString(url, data, contentType, false, logTitle);
    }

    public static String httpPostFormData(String url, Map<String, String> data, String logTitle) throws Exception {
        String guid = GenerateUtil.genUUID();
        log.info(String.format("httpPost(%s)(%s): url=[%s], data=[%s]", guid, logTitle, url, data));
        StringBuffer result = new StringBuffer();

        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            post.setHeader("User-Agent", "User-Agent");
            List<NameValuePair> urlParameters = new ArrayList();
            Iterator var8 = data.keySet().iterator();

            while(var8.hasNext()) {
                String key = (String)var8.next();
                urlParameters.add(new BasicNameValuePair(key, (String)data.get(key)));
            }

            post.setEntity(new UrlEncodedFormEntity(urlParameters));
            HttpResponse response = client.execute(post);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = "";

            while((line = rd.readLine()) != null) {
                result.append(line);
            }

            log.info(String.format("httpPost(%s)(%s) success: url=[%s], result=[%s]", guid, logTitle, url, result.toString()));
        } catch (Exception var11) {
            log.error(String.format("httpPost(%s)(%s) fail: url=[%s]", guid, logTitle, url), var11);
        }

        return result.toString();
    }

    private static JsonObject httpPost(String url, JsonObject jsonParam, boolean noNeedResponse, String logTitle) {
        JsonObject jsonResult = null;
        String strResult = httpPostString(url, jsonParam, noNeedResponse, logTitle);
        if (!Strings.isNullOrEmpty(strResult)) {
            jsonResult = JSONUtil.fromJson(strResult, JsonObject.class);
        }

        return jsonResult;
    }

    private static String httpPostString(String url, JsonObject jsonParam, boolean noNeedResponse, String logTitle) {
        return httpPostString(url, jsonParam == null ? null : jsonParam.toString(), "application/json", noNeedResponse, logTitle);
    }

    private static String httpPostString(String url, String data, String contentType, boolean noNeedResponse, String logTitle) {
        String guid = GenerateUtil.genUUID();
        log.info(String.format("httpPost(%s)(%s): url=[%s], data=[%s]", guid, logTitle, url, data));
        HttpClient client = HttpClientBuilder.create().build();
        String strResult = null;
        HttpPost request = new HttpPost(url.trim());

        try {
            if (!Strings.isNullOrEmpty(data)) {
                StringEntity entity = new StringEntity(data, "UTF-8");
                entity.setContentEncoding("UTF-8");
                if (!Strings.isNullOrEmpty(contentType)) {
                    entity.setContentType(contentType);
                }

                request.setEntity(entity);
            }

            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                try {
                    HttpEntity entity = response.getEntity();
                    strResult = EntityUtils.toString(response.getEntity(), "UTF-8");
                    if (logTitle != null) {
                        log.info(String.format("httpPost(%s)(%s) success: url=[%s], result=[%s]", guid, logTitle, url, strResult));
                    }

                    return noNeedResponse ? null : strResult;
                } catch (Exception var12) {
                    log.error(String.format("httpPost(%s)(%s) fail: url=[%s]", guid, logTitle, url), var12);
                    throw new RuntimeException(var12.getMessage() + "http statusCode" + statusCode, var12);
                }
            } else {
                log.error(String.format("httpPost(%s)(%s) fail: url=[%s], statusCode=[%d]", guid, logTitle, url, statusCode));
                throw new RuntimeException("http statusCode" + statusCode);
            }
        } catch (IOException var13) {
            log.error(String.format("httpPost(%s)(%s) fail: url=[%s]", guid, logTitle, url), var13);
            throw new RuntimeException(var13);
        }
    }

    public static String httpGetString(String url, Map<String, Object> params, String logTitle) {
        if (params != null && params.size() > 0) {
            url = url + "?" + Joiner.on("&").withKeyValueSeparator("=").join(params);
        }

        return httpGetString(url, logTitle);
    }

    public static String httpGetString(String url, Map<String, Object> params, Map<String, String> headers, String logTitle) {
        if (params != null && params.size() > 0) {
            url = url + "?" + Joiner.on("&").withKeyValueSeparator("=").join(params);
        }

        return httpGetString(url, logTitle, headers);
    }

    public static String httpGetString(String url, String logTitle, Map<String, String> headers) {
        String guid = GenerateUtil.genUUID();
        if (logTitle != null) {
            log.info(String.format("httpGet(%s)(%s): url=[%s]", guid, logTitle, url));
        }

        String strResult = null;

        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url.trim());
            Iterator var7 = headers.entrySet().iterator();

            while(var7.hasNext()) {
                Map.Entry<String, String> e = (Map.Entry)var7.next();
                request.addHeader((String)e.getKey(), (String)e.getValue());
            }

            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                strResult = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.info(String.format("httpGet(%s)(%s) success: url=[%s], result=[%s]", guid, logTitle, url, strResult));
            } else {
                log.error(String.format("httpGet(%s)(%s) fail: url=[%s], statusCode=[%d]", guid, logTitle, url, statusCode));
                throw new RuntimeException("statusCode is " + statusCode);
            }
        } catch (IOException var9) {
            log.error(String.format("httpGet(%s)(%s) fail: url=[%s]", guid, logTitle, url), var9);
            throw new RuntimeException("httpGet fail");
        }

        return strResult;
    }

    public static String httpGetString(String url, String logTitle) {
        String guid = GenerateUtil.genUUID();
        if (logTitle != null) {
            log.info(String.format("httpGet(%s)(%s): url=[%s]", guid, logTitle, url));
        }

        String strResult = null;

        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url.trim());
            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                strResult = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.info(String.format("httpGet(%s)(%s) success: url=[%s], result=[%s]", guid, logTitle, url, strResult));
            } else {
                log.error(String.format("httpGet(%s)(%s) fail: url=[%s], statusCode=[%d]", guid, logTitle, url, statusCode));
            }
        } catch (IOException var8) {
            log.error(String.format("httpGet(%s)(%s) fail: url=[%s]", guid, logTitle, url), var8);
        }

        return strResult;
    }

    public static String httpPostString(String url, String data, Map<String, String> headers, String logTitle) {
        return httpPostString(url, data, headers, (String)null, false, logTitle, null, null);
    }

    public static String httpPostString(String url, String data, Map<String, String> headers, String contentType, String logTitle) {
        return httpPostString(url, data, headers, contentType, false, logTitle, null, null);
    }

    public static String httpPostString(String url, String data, Map<String, String> headers, String logTitle, Integer connectTimeout, Integer socketTimeout) {
        return httpPostString(url, data, headers, (String)null, false, logTitle, connectTimeout, socketTimeout);
    }

    public static String httpPostString(String url, String data, Map<String, String> headers, String contentType, String logTitle, Integer connectTimeout, Integer socketTimeout) {
        return httpPostString(url, data, headers, contentType, false, logTitle, connectTimeout, socketTimeout);
    }

    private static String httpPostString(String url, String data, Map<String,String> headers, String contentType, boolean noNeedResponse, String logTitle, Integer connectTimeout, Integer socketTimeout) {
        String guid = GenerateUtil.genUUID();
        log.info(String.format("httpPost(%s)(%s): url=[%s], data=[%s]", guid, logTitle, url, data));
        HttpClient client = HttpClientBuilder.create().build();
        String strResult = null;
        HttpPost request = new HttpPost(url.trim());
        if(null != connectTimeout || null != socketTimeout) {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
            request.setConfig(requestConfig);
        }
        try {
            if (!Strings.isNullOrEmpty(data)) {
                StringEntity entity = new StringEntity(data, "UTF-8");
                entity.setContentEncoding("UTF-8");
                if (!Strings.isNullOrEmpty(contentType)) {
                    entity.setContentType(contentType);
                }

                request.setEntity(entity);
            }

            if(null != headers) {
                for(String headerKey : headers.keySet()) {
                    request.setHeader(headerKey,headers.get(headerKey));
                }
            }

            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                try {
                    HttpEntity entity = response.getEntity();
                    strResult = EntityUtils.toString(response.getEntity(), "UTF-8");
                    if (logTitle != null) {
                        log.info(String.format("httpPost(%s)(%s) success: url=[%s], result=[%s]", guid, logTitle, url, strResult));
                    }

                    return noNeedResponse ? null : strResult;
                } catch (Exception var12) {
                    log.error(String.format("httpPost(%s)(%s) fail: url=[%s]", guid, logTitle, url), var12);
                    throw new RuntimeException(var12.getMessage() + "http statusCode" + statusCode, var12);
                }
            } else {
                log.error(String.format("httpPost(%s)(%s) fail: url=[%s], statusCode=[%d]", guid, logTitle, url, statusCode));
                throw new RuntimeException("http statusCode" + statusCode);
            }
        } catch (IOException var13) {
            log.error(String.format("httpPost(%s)(%s) fail: url=[%s]", guid, logTitle, url), var13);
            throw new RuntimeException(var13);
        }
    }

    public static boolean isHttpExist(String url) {
        try {
            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection con = (HttpURLConnection)(new URL(url)).openConnection();
            con.setRequestMethod("HEAD");
            return con.getResponseCode() == 200;
        } catch (Exception var2) {
            return false;
        }
    }

    public interface IDownloadListener {
        void onProgress(int var1);

        void onFinish();

        void onFail(String var1);

        boolean getCancelUpdate();
    }
}